"""
Author: HuWen
@file: testapi.py
@dateTime: 2025/9/25 17:13
加油加油！！！
"""
import requests
import json
from datetime import datetime
import logging

# 配置日志记录（持久化请求/响应信息）
logging.basicConfig(
    filename='hazardous_waste_import.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

def parse_hazardous_waste_from_document():
    """
    功能：从《危废名录.pdf》解析所有危废数据，生成接口所需参数列表
    返回：危废参数列表（每个元素为一条危废的接口参数）
    """
    # 基于《危废名录.pdf》附表1-21至1-109内容，自动解析的危废数据（示例包含多类别典型记录，可扩展至全名录）
    parsed_waste_list = [
        # HW01 医疗废物（源自文档1-21）
        {
            "wasteName": "感染性废物",
            "wasteCode": "841-001-01",
            "wasteCategory": "HW01",
            "hazardousFeature": "infectivity",  # 文档中危险特性为In，对应感染性
            "wasteState": "solid_state",
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW01医疗废物类危废，产生于卫生行业",
            "physicalProperties": "固态，含病原体，具有感染性危险特性",
            "enterpriseId": "1820379858379681793"
        },
        {
            "wasteName": "损伤性废物",
            "wasteCode": "841-002-01",
            "wasteCategory": "HW01",
            "hazardousFeature": "infectivity",
            "wasteState": "solid_state",
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW01医疗废物类危废，产生于卫生行业",
            "physicalProperties": "固态（如针头、刀片），具有感染性危险特性",
            "enterpriseId": "1820379858379681793"
        },
        # HW02 医药废物（源自文档1-21、1-23）
        {
            "wasteName": "化学合成原料药生产过程中产生的蒸馏及反应残余物",
            "wasteCode": "271-001-02",
            "wasteCategory": "HW02",
            "hazardousFeature": "toxicity",  # 文档中危险特性为T，对应毒性
            "wasteState": "solid_state",
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW02医药废物类危废，产生于化学药品原料药制造行业",
            "physicalProperties": "固态残余物，具有毒性危险特性",
            "enterpriseId": "1820379858379681793"
        },
        {
            "wasteName": "兽药生产过程中产生的废母液、反应基和培养基废物",
            "wasteCode": "275-006-02",
            "wasteCategory": "HW02",
            "hazardousFeature": "toxicity",
            "wasteState": "solid_state",
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW02医药废物类危废，产生于兽用药品制造行业",
            "physicalProperties": "固态或半固态，具有毒性危险特性",
            "enterpriseId": "1820379858379681793"
        },
        # HW04 农药废物（源自文档1-24）
        {
            "wasteName": "甲拌磷生产过程中二乙基二硫代磷酸过滤产生的残余物",
            "wasteCode": "263-003-04",
            "wasteCategory": "HW04",
            "hazardousFeature": "toxicity",
            "wasteState": "solid_state",
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW04农药废物类危废，产生于农药制造行业",
            "physicalProperties": "固态残渣，具有毒性危险特性",
            "enterpriseId": "1820379858379681793"
        },
        # HW08 废矿物油与含矿物油废物（源自文档1-31）
        {
            "wasteName": "车辆、轮船及其它机械维修过程中产生的废发动机油、制动器油、自动变速器油、齿轮油等废润滑油",
            "wasteCode": "900-214-08",
            "wasteCategory": "HW08",
            "hazardousFeature": "toxicity,ignitability",  # 文档中危险特性为T,I，对应毒性、易燃性
            "wasteState": "liquid",  # 废润滑油为液态，修正默认值
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW08废矿物油类危废，产生于非特定行业",
            "physicalProperties": "液态，呈深色粘稠状，具有毒性、易燃性危险特性",
            "enterpriseId": "1820379858379681793"
        },
        # HW49 其他废物（源自文档1-68）
        {
            "wasteName": "废电路板（包括已拆除或者未拆除元器件的废弃电路板）",
            "wasteCode": "900-045-49",
            "wasteCategory": "HW49",
            "hazardousFeature": "toxicity",
            "wasteState": "solid_state",
            "detailDesc": "依据《国家危险废物名录(2025年版)》，属于HW49其他废物类危废，产生于非特定行业",
            "physicalProperties": "固态，含重金属，具有毒性危险特性",
            "enterpriseId": "1820379858379681793"
        }
        # 注：可根据《危废名录.pdf》完整附表，继续扩展HW03、HW05-HW07、HW09-HW48、HW50等所有类别的危废记录
    ]

    logging.info(f"从《危废名录.pdf》解析完成，共获取{len(parsed_waste_list)}条危废数据")
    print(f"✅ 从《危废名录.pdf》解析完成，共获取{len(parsed_waste_list)}条危废数据（示例数据，可扩展至全名录）")
    return parsed_waste_list

def batch_import_to_api(waste_list):
    """
    功能：将解析后的危废数据批量通过接口写入
    参数：waste_list - 解析后的危废参数列表
    返回：导入结果统计（成功数、失败数、失败详情）
    """
    # 接口基础配置
    api_url = "http://192.168.11.91:32565/hazardous-waste/hazardous_waste_information"
    headers = {
        "Content-Type": "application/json",
        "cup-auth":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZW5hbnRfaWQiOiIwMDAwMDAiLCJ1c2VyX25hbWUiOiIxMzYwODMzOTU1NyIsImRlcHRfaWRzIjoiMTgyMDM3OTg1ODM3OTY4MTc5MyIsInJlYWxfbmFtZSI6IkdPT0TlhYjnlJ8iLCJjbGllbnRfaWQiOiJzYWJlciIsInJvbGVfaWQiOiIxNjk2MDAxNDQwMDU3ODQzMDAyIiwic2NvcGUiOlsiYWxsIl0sIm9hdXRoX2lkIjoiIiwiZGVwdF90eXBlIjoiMiIsImV4cCI6MTc1OTE0OTgzMiwicm9sZV9hbGlhcyI6ImNvbXBhbnksY29tcGFueUxlYWRlcixiaWdfcm9sZSIsImp0aSI6ImUyMmEyMTg1LTM0MjAtNDZlZi04MGVlLTE1ZGRiZjAxZGNmZSIsImtleSI6ImN1cGJhc2UiLCJkZXB0X25hbWUiOiLnpo_lu7rkvJjlipvnibnmnZDmlpnmnInpmZDlhazlj7giLCJhdmF0YXIiOiIvZGVmLWJ1Y2tldC8yMDI1MDQwNy8xNzQzOTkzMzkwMDcyLmpwZyIsImF1dGhvcml0aWVzIjpbImNvbXBhbnlMZWFkZXIiLCJiaWdfcm9sZSIsImNvbXBhbnkiXSwicm9sZV9uYW1lIjoiY29tcGFueSxjb21wYW55TGVhZGVyLGJpZ19yb2xlIiwibGljZW5zZSI6InBvd2VyZWQgYnkgY3VweCIsImZ1bGxfbmFtZSI6Iuemj-W7uuS8mOWKm-eJueadkOaWmeaciemZkOWFrOWPuCIsInBvc3RfaWQiOiIxMTIzNTk4ODE3NzM4Njc1MjA4IiwidXNlcl9pZCI6IjE5MDcyODYxMTQ2MDYxNjYwMTgiLCJwaG9uZSI6IjEzNjA4MzM5NTU3Iiwibmlja19uYW1lIjoiR09PROWFiOeUnyIsImRldGFpbCI6eyJ0eXBlIjoid2ViIiwicmVhbE5hbWUiOiJHT09E5YWI55SfIn0sImRlcHRfaWQiOiIxODIwMzc5ODU4Mzc5NjgxNzkzIiwiYWNjb3VudCI6IjEzNjA4MzM5NTU3In0.iEwjhZ0zP5EBWLAK_O14hkGamF4xS_tjgT79J4hJSjk"
        # 若接口需要认证（如Token），可在此添加，示例：
        # "Authorization": "Bearer your_access_token"
    }

    # 统计变量
    success_count = 0
    fail_count = 0
    fail_details = []

    logging.info(f"开始批量导入危废数据，目标接口：{api_url}，总条数：{len(waste_list)}")
    print(f"\n🚀 开始批量导入危废数据，目标接口：{api_url}，总条数：{len(waste_list)}")

    # 循环导入每条危废数据
    for idx, waste in enumerate(waste_list, 1):
        print(f"\n【第{idx}/{len(waste_list)}条】处理废物代码：{waste['wasteCode']}（{waste['wasteName']}）")
        logging.info(f"处理第{idx}条危废数据，废物代码：{waste['wasteCode']}，废物名称：{waste['wasteName']}")

        try:
            # 发送POST请求
            response = requests.post(
                url=api_url,
                data=json.dumps(waste, ensure_ascii=False),  # 避免中文乱码
                headers=headers,
                timeout=20
            )

            # 处理响应
            response.raise_for_status()  # 捕获4xx/5xx错误
            response_json = response.json()

            # 验证导入结果（核心字段匹配）
            returned_code = response_json.get("data", {}).get("wasteCode")
            if returned_code == waste["wasteCode"]:
                success_count += 1
                msg = f"导入成功！响应状态码：{response.status_code}，废物代码匹配：{returned_code}"
                print(f"✅ {msg}")
                logging.info(f"第{idx}条导入成功：{msg}，响应内容：{json.dumps(response_json, ensure_ascii=False)}")
            else:
                fail_count += 1
                err_msg = f"导入后字段不匹配，预期代码：{waste['wasteCode']}，实际返回：{returned_code}"
                fail_details.append(f"第{idx}条（{waste['wasteCode']}）：{err_msg}")
                print(f"⚠️ {err_msg}")
                logging.warning(f"第{idx}条导入警告：{err_msg}，响应内容：{json.dumps(response_json, ensure_ascii=False)}")

        except requests.exceptions.Timeout:
            fail_count += 1
            err_msg = "请求超时（20秒）"
            fail_details.append(f"第{idx}条（{waste['wasteCode']}）：{err_msg}")
            print(f"❌ {err_msg}")
            logging.error(f"第{idx}条导入失败：{err_msg}，废物代码：{waste['wasteCode']}")

        except requests.exceptions.ConnectionError:
            fail_count += 1
            err_msg = "接口连接失败（地址或服务异常）"
            fail_details.append(f"第{idx}条（{waste['wasteCode']}）：{err_msg}")
            print(f"❌ {err_msg}")
            logging.error(f"第{idx}条导入失败：{err_msg}，接口地址：{api_url}")

        except requests.exceptions.HTTPError as e:
            fail_count += 1
            err_msg = f"HTTP错误，状态码：{e.response.status_code}，响应内容：{e.response.text[:100]}（截断）"
            fail_details.append(f"第{idx}条（{waste['wasteCode']}）：{err_msg}")
            print(f"❌ {err_msg}")
            logging.error(f"第{idx}条导入失败：{err_msg}，废物代码：{waste['wasteCode']}")

        except Exception as e:
            fail_count += 1
            err_msg = f"未知异常：{str(e)[:80]}（截断）"
            fail_details.append(f"第{idx}条（{waste['wasteCode']}）：{err_msg}")
            print(f"❌ {err_msg}")
            logging.error(f"第{idx}条导入失败：{err_msg}，废物代码：{waste['wasteCode']}")

    # 输出导入总结
    print(f"\n" + "="*60)
    print(f"📊 批量导入完成！总条数：{len(waste_list)}，成功：{success_count}，失败：{fail_count}")
    if fail_details:
        print(f"\n❌ 失败详情：")
        for detail in fail_details:
            print(f"   - {detail}")
    print("="*60)

    logging.info(f"批量导入结束，统计：总{len(waste_list)}条，成功{success_count}条，失败{fail_count}条")
    return {
        "total": len(waste_list),
        "success": success_count,
        "fail": fail_count,
        "fail_details": fail_details
    }

# 主执行流程
if __name__ == "__main__":
    print("="*70)
    print("📋 基于《危废名录.pdf》的危废信息自动解析与接口录入工具")
    print("="*70)

    # 1. 从文档解析危废数据
    waste_data_list = parse_hazardous_waste_from_document()

    # 2. 批量导入接口
    if waste_data_list:
        import_result = batch_import_to_api(waste_data_list)
    else:
        print("❌ 未从《危废名录.pdf》解析到有效危废数据，导入终止")
        logging.error("未解析到有效危废数据，导入终止")